package socket2redis;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @author fangjiaxiaobai@gmail.com[公众号：方家小白]
 * @date 2020-06-24 17:51
 * @since 1.0.0
 */
public class SocketRedisClient {

    private String host;

    private int port;

    private int bufferSize = 128;

    InputStream inputStream = null;
    OutputStream outputStream = null;
    Socket socket = null;

    public SocketRedisClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public SocketRedisClient(String host, int port, int bufferSize) {
        this.host = host;
        this.port = port;
        if (this.bufferSize < bufferSize) {
            this.bufferSize = bufferSize;
        }
    }

    public String exec(String cmd) throws IOException {
        return this.exec(cmd, false);
    }

    public String exec(String cmd, boolean showLog) throws IOException {
        init();
        if (!cmd.endsWith("\r\n")) {
            cmd += "\r\n";
        }

        byte[] bytes = new byte[128];
        outputStream.write(cmd.getBytes(StandardCharsets.UTF_8));
        int length = inputStream.read(bytes);
        String result = new String(bytes, 0, length, StandardCharsets.UTF_8);
        result = result.replace("\r\n", "");
        if (showLog) {
            System.out.println("执行命令:" + cmd.replace("\r\n", "") + "的结果为: 【" + result + "】");
        }
        return result;
    }

    public void releases() throws IOException {
        if (outputStream != null) {
            outputStream.close();
        }
        if (inputStream != null) {
            inputStream.close();
        }
        if (socket != null) {
            socket.close();
        }
    }

    private void init() throws IOException {
        if (socket == null) {
            socket = new Socket(host, port);
        }
        if (inputStream == null) {
            this.inputStream = socket.getInputStream();
        }
        if (outputStream == null) {
            this.outputStream = socket.getOutputStream();
        }
    }


}
